<?php

/**
 * Plugin to initialize application state
 *
 * @uses       Zend_Controller_Plugin_Abstract
 * @version    $Id: $
 */
class WSB_Controller_Plugin_Profiler extends Zend_Controller_Plugin_Abstract
{
    /**
     * Called before an action is dispatched by Zend_Controller_Dispatcher.
     *
     * This callback allows for proxy or filter behavior.  By altering the
     * request and resetting its dispatched flag (via
     * {@link Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}),
     * the current action may be skipped.
     *
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     */
    public function dispatchLoopShutdown()
    {
		$profiler	  = Zend_Db_Table_Abstract::getDefaultAdapter()->getProfiler();
		$totalTime    = $profiler->getTotalElapsedSecs();
		$queryCount   = $profiler->getTotalNumQueries();
		$longestTime  = 0;
		$longestQuery = null;

		$infos = '';

		foreach ($profiler->getQueryProfiles() as $query) {
			/*
		    if ($query->getElapsedSecs() > $longestTime) {
		        $longestTime  = $query->getElapsedSecs();
		        $longestQuery = $query->getQuery();
		    }
		    */
			$infos .= $query->getQuery();
			$infos .= "<hr />";
		}

		$infos .= 'Executed ' . $queryCount . ' queries in ' . $totalTime . ' seconds' . "<br />\n";
		$infos .= 'Average query length: ' . $totalTime / $queryCount . ' seconds' . "<br />\n";
		$infos .= 'Queries per second: ' . $queryCount / $totalTime . "<br />\n";
		$infos .= 'Longest query length: ' . $longestTime . "<br />\n";
		$infos .= "Longest query: \n" . $longestQuery . "<br />\n";
		$this->getResponse()->append('debug', $infos);
    }

}
